<template>
  <div class="notes-container">
    <h1 class="page-title">我的笔记</h1>
    
    <div class="filters-container">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索笔记..." 
          class="search-input"
          @input="handleSearch"
        />
        <i class="icon icon-search"></i>
      </div>
      
      <div class="filter-options">
        <div class="filter-group">
          <label>按文档筛选:</label>
          <select v-model="documentFilter" @change="applyFilters" class="filter-select">
            <option value="">全部文档</option>
            <option v-for="doc in documents" :key="doc._id" :value="doc._id">
              {{ doc.title }}
            </option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>按章节筛选:</label>
          <select v-model="chapterFilter" @change="applyFilters" class="filter-select">
            <option value="">全部章节</option>
            <option v-for="chapter in chapters" :key="chapter" :value="chapter">
              {{ chapter }}
            </option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>排序方式:</label>
          <select v-model="sortOption" @change="applyFilters" class="filter-select">
            <option value="newest">最新添加</option>
            <option value="oldest">最早添加</option>
            <option value="document">按文档</option>
            <option value="chapter">按章节</option>
          </select>
        </div>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="fetchNotes" class="btn btn-primary">重试</button>
    </div>
    
    <div v-else-if="filteredNotes.length === 0" class="empty-state">
      <div class="empty-icon">📝</div>
      <h2>暂无笔记</h2>
      <p v-if="hasFilters">没有符合当前筛选条件的笔记，请尝试调整筛选条件。</p>
      <p v-else>您还没有添加任何笔记。浏览知识卡片时可以添加笔记。</p>
      <router-link to="/cards" class="btn btn-primary">浏览知识卡片</router-link>
    </div>
    
    <div v-else class="notes-list">
      <div v-for="note in filteredNotes" :key="note._id" class="note-card">
        <div class="note-header">
          <div class="note-meta">
            <span class="note-document">{{ getDocumentTitle(note.cardId) }}</span>
            <span class="note-chapter">{{ getCardChapter(note.cardId) }}</span>
          </div>
          <div class="note-actions">
            <button @click="editNote(note)" class="btn-icon" title="编辑笔记">
              <i class="icon icon-edit"></i>
            </button>
            <button @click="confirmDeleteNote(note)" class="btn-icon" title="删除笔记">
              <i class="icon icon-delete"></i>
            </button>
          </div>
        </div>
        
        <div class="note-card-title">
          <router-link :to="`/cards/${note.cardId}`" class="card-link">
            {{ getCardTitle(note.cardId) }}
          </router-link>
        </div>
        
        <div v-if="editingNoteId === note._id" class="note-editor">
          <textarea 
            v-model="editNoteContent" 
            class="note-textarea"
            rows="5"
          ></textarea>
          <div class="editor-actions">
            <button @click="cancelEdit" class="btn btn-outline-secondary">取消</button>
            <button @click="saveNoteEdit(note)" class="btn btn-primary">保存</button>
          </div>
        </div>
        
        <div v-else class="note-content" v-html="note.content"></div>
        
        <div class="note-footer">
          <span class="note-date">{{ formatDate(note.updatedAt || note.createdAt) }}</span>
        </div>
      </div>
    </div>
    
    <div v-if="filteredNotes.length > 0" class="pagination">
      <button 
        @click="prevPage" 
        class="btn btn-outline-primary" 
        :disabled="currentPage === 1"
      >
        上一页
      </button>
      <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
      <button 
        @click="nextPage" 
        class="btn btn-outline-primary" 
        :disabled="currentPage === totalPages"
      >
        下一页
      </button>
    </div>
    
    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay">
      <div class="modal-container">
        <div class="modal-header">
          <h3>确认删除</h3>
          <button @click="showDeleteConfirm = false" class="btn-close">&times;</button>
        </div>
        <div class="modal-body">
          <p>确定要删除这条笔记吗？此操作无法撤销。</p>
        </div>
        <div class="modal-footer">
          <button @click="showDeleteConfirm = false" class="btn btn-outline-secondary">取消</button>
          <button @click="deleteNote" class="btn btn-danger">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { userApi } from '@/services/api';
import { documentApi } from '@/services/api';
import { cardApi } from '@/services/api';

export default {
  name: 'NotesView',
  setup() {
    // 状态
    const notes = ref([]);
    const documents = ref([]);
    const cards = ref({});  // 卡片缓存，格式：{cardId: cardData}
    const chapters = ref([]);
    const loading = ref(true);
    const error = ref(null);
    
    // 筛选和排序
    const searchQuery = ref('');
    const documentFilter = ref('');
    const chapterFilter = ref('');
    const sortOption = ref('newest');
    
    // 编辑状态
    const editingNoteId = ref(null);
    const editNoteContent = ref('');
    
    // 删除确认
    const showDeleteConfirm = ref(false);
    const noteToDelete = ref(null);
    
    // 分页
    const currentPage = ref(1);
    const pageSize = 10;
    
    // 获取用户笔记
    const fetchNotes = async () => {
      loading.value = true;
      error.value = null;
      
      try {
        const response = await userApi.getNotes();
        notes.value = response.data;
        
        // 获取相关卡片信息
        await fetchCardInfo();
        
        // 提取所有章节
        const uniqueChapters = new Set();
        for (const cardId in cards.value) {
          if (cards.value[cardId].chapter) {
            uniqueChapters.add(cards.value[cardId].chapter);
          }
        }
        chapters.value = Array.from(uniqueChapters);
        
        // 获取文档列表
        const docsResponse = await documentApi.getUserDocuments();
        documents.value = docsResponse.data;
      } catch (err) {
        error.value = err.message || '获取笔记失败';
        console.error('获取笔记失败:', err);
      } finally {
        loading.value = false;
      }
    };
    
    // 获取卡片信息
    const fetchCardInfo = async () => {
      const cardIds = new Set(notes.value.map(note => note.cardId));
      
      for (const cardId of cardIds) {
        if (!cards.value[cardId]) {
          try {
            const response = await cardApi.getById(cardId);
            cards.value[cardId] = response.data;
          } catch (err) {
            console.error(`获取卡片 ${cardId} 信息失败:`, err);
            // 设置一个默认值，避免UI错误
            cards.value[cardId] = {
              title: '未知卡片',
              chapter: '未知章节',
              documentId: null
            };
          }
        }
      }
    };
    
    // 应用筛选和排序
    const applyFilters = () => {
      currentPage.value = 1; // 重置页码
    };
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1; // 重置页码
    };
    
    // 编辑笔记
    const editNote = (note) => {
      editingNoteId.value = note._id;
      editNoteContent.value = note.content;
    };
    
    // 取消编辑
    const cancelEdit = () => {
      editingNoteId.value = null;
      editNoteContent.value = '';
    };
    
    // 保存笔记编辑
    const saveNoteEdit = async (note) => {
      try {
        await userApi.updateNote(note._id, {
          content: editNoteContent.value,
          cardId: note.cardId
        });
        
        // 更新本地数据
        const index = notes.value.findIndex(n => n._id === note._id);
        if (index !== -1) {
          notes.value[index].content = editNoteContent.value;
          notes.value[index].updatedAt = new Date().toISOString();
        }
        
        cancelEdit();
      } catch (err) {
        console.error('更新笔记失败:', err);
        error.value = err.message || '更新笔记失败';
      }
    };
    
    // 确认删除笔记
    const confirmDeleteNote = (note) => {
      noteToDelete.value = note;
      showDeleteConfirm.value = true;
    };
    
    // 删除笔记
    const deleteNote = async () => {
      if (!noteToDelete.value) return;
      
      try {
        await userApi.deleteNote(noteToDelete.value._id);
        
        // 从本地数据中移除
        notes.value = notes.value.filter(note => note._id !== noteToDelete.value._id);
        
        showDeleteConfirm.value = false;
        noteToDelete.value = null;
      } catch (err) {
        console.error('删除笔记失败:', err);
        error.value = err.message || '删除笔记失败';
      }
    };
    
    // 获取卡片标题
    const getCardTitle = (cardId) => {
      return cards.value[cardId]?.title || '未知卡片';
    };
    
    // 获取卡片章节
    const getCardChapter = (cardId) => {
      return cards.value[cardId]?.chapter || '未知章节';
    };
    
    // 获取文档标题
    const getDocumentTitle = (cardId) => {
      const documentId = cards.value[cardId]?.documentId;
      if (!documentId) return '未知文档';
      
      const document = documents.value.find(doc => doc._id === documentId);
      return document?.title || '未知文档';
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    // 分页导航
    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };
    
    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };
    
    // 计算属性
    
    // 筛选和排序后的笔记
    const filteredNotes = computed(() => {
      let result = [...notes.value];
      
      // 应用搜索
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        result = result.filter(note => 
          note.content.toLowerCase().includes(query) || 
          getCardTitle(note.cardId).toLowerCase().includes(query)
        );
      }
      
      // 应用文档筛选
      if (documentFilter.value) {
        result = result.filter(note => {
          const card = cards.value[note.cardId];
          return card && card.documentId === documentFilter.value;
        });
      }
      
      // 应用章节筛选
      if (chapterFilter.value) {
        result = result.filter(note => {
          const card = cards.value[note.cardId];
          return card && card.chapter === chapterFilter.value;
        });
      }
      
      // 应用排序
      switch (sortOption.value) {
        case 'newest':
          result.sort((a, b) => new Date(b.updatedAt || b.createdAt) - new Date(a.updatedAt || a.createdAt));
          break;
        case 'oldest':
          result.sort((a, b) => new Date(a.updatedAt || a.createdAt) - new Date(b.updatedAt || b.createdAt));
          break;
        case 'document':
          result.sort((a, b) => {
            const docA = getDocumentTitle(a.cardId);
            const docB = getDocumentTitle(b.cardId);
            return docA.localeCompare(docB);
          });
          break;
        case 'chapter':
          result.sort((a, b) => {
            const chapterA = getCardChapter(a.cardId);
            const chapterB = getCardChapter(b.cardId);
            return chapterA.localeCompare(chapterB);
          });
          break;
      }
      
      return result;
    });
    
    // 分页后的笔记
    const paginatedNotes = computed(() => {
      const start = (currentPage.value - 1) * pageSize;
      const end = start + pageSize;
      return filteredNotes.value.slice(start, end);
    });
    
    // 总页数
    const totalPages = computed(() => {
      return Math.ceil(filteredNotes.value.length / pageSize) || 1;
    });
    
    // 是否有筛选条件
    const hasFilters = computed(() => {
      return searchQuery.value || documentFilter.value || chapterFilter.value;
    });
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchNotes();
    });
    
    return {
      notes,
      documents,
      chapters,
      loading,
      error,
      searchQuery,
      documentFilter,
      chapterFilter,
      sortOption,
      editingNoteId,
      editNoteContent,
      showDeleteConfirm,
      currentPage,
      filteredNotes: paginatedNotes,
      totalPages,
      hasFilters,
      fetchNotes,
      applyFilters,
      handleSearch,
      editNote,
      cancelEdit,
      saveNoteEdit,
      confirmDeleteNote,
      deleteNote,
      getCardTitle,
      getCardChapter,
      getDocumentTitle,
      formatDate,
      prevPage,
      nextPage
    };
  }
};
</script>

<style scoped>
.notes-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.page-title {
  font-size: 2rem;
  margin-bottom: 20px;
  color: #333;
}

.filters-container {
  margin-bottom: 20px;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-box {
  position: relative;
  margin-bottom: 15px;
}

.search-input {
  width: 100%;
  padding: 10px 15px;
  padding-right: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.search-input:focus {
  outline: none;
  border-color: #1976d2;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.icon-search {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-group {
  flex: 1;
  min-width: 200px;
}

.filter-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 0.9rem;
  color: #666;
}

.filter-select {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  font-size: 0.9rem;
}

.filter-select:focus {
  outline: none;
  border-color: #1976d2;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #3498db;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-container {
  text-align: center;
  padding: 30px;
  background-color: #fff3f3;
  border-radius: 8px;
  margin: 20px 0;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 15px;
}

.empty-state h2 {
  font-size: 1.5rem;
  margin-bottom: 10px;
  color: #333;
}

.empty-state p {
  color: #666;
  margin-bottom: 20px;
}

.notes-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.note-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.note-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.note-meta {
  display: flex;
  gap: 10px;
}

.note-document {
  background-color: #e3f2fd;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.note-chapter {
  background-color: #e8f5e9;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.note-actions {
  display: flex;
  gap: 5px;
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  color: #666;
  transition: background-color 0.2s;
}

.btn-icon:hover {
  background-color: #f1f1f1;
  color: #333;
}

.note-card-title {
  margin-bottom: 15px;
  font-size: 1.2rem;
  font-weight: 500;
}

.card-link {
  color: #1976d2;
  text-decoration: none;
}

.card-link:hover {
  text-decoration: underline;
}

.note-content {
  line-height: 1.6;
  color: #333;
  margin-bottom: 15px;
}

.note-footer {
  display: flex;
  justify-content: flex-end;
  color: #999;
  font-size: 0.8rem;
}

.note-date {
  font-style: italic;
}

.note-editor {
  margin-bottom: 15px;
}

.note-textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: inherit;
  font-size: inherit;
  resize: vertical;
  margin-bottom: 10px;
}

.note-textarea:focus {
  outline: none;
  border-color: #1976d2;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.editor-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  gap: 15px;
}

.page-info {
  font-size: 0.9rem;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.2rem;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: background-color 0.2s;
}

.btn-primary {
  background-color: #1976d2;
  color: white;
}

.btn-primary:hover {
  background-color: #1565c0;
}

.btn-outline-primary {
  background-color: transparent;
  color: #1976d2;
  border: 1px solid #1976d2;
}

.btn-outline-primary:hover {
  background-color: #e3f2fd;
}

.btn-outline-secondary {
  background-color: transparent;
  color: #757575;
  border: 1px solid #757575;
}

.btn-outline-secondary:hover {
  background-color: #f5f5f5;
}

.btn-danger {
  background-color: #d32f2f;
  color: white;
}

.btn-danger:hover {
  background-color: #c62828;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-options {
    flex-direction: column;
    gap: 10px;
  }
  
  .filter-group {
    min-width: 100%;
  }
}
</style> 